import { getCartInfo } from "../../../../api/api"
import React, { useState, useContext, useEffect, useRef } from "react";
import Link from "next/link";
import CartContext from "../../../../helpers/cart";
import { Container, Row, Col, Media, Input, Button, Modal, ModalHeader, ModalBody, Form, Label, Dropdown, DropdownToggle, DropdownMenu, DropdownItem, ButtonGroup, UncontrolledDropdown } from "reactstrap";
import { CurrencyContext } from "../../../../helpers/Currency/CurrencyContext";
import cart from "../../../../public/assets/images/icon-empty-cart.png";
// import { getCartInfo } from "../.."
import { fileServerUrl } from "../../../../config/index.json";
import { getTwoDecimal } from "../../../../tools/tools";
import { changeProductCount, removeCartProduct } from "../../../../api/api";
import { debounce } from "lodash";
import { toast } from "react-toastify";
import { useRouter } from 'next/router';

const AdminOrderBinPage = () => {
  const context = useContext(CartContext);
  const cartItems = context.state;
  const curContext = useContext(CurrencyContext);
  const symbol = curContext.state.symbol;
  // const total = context.cartTotal;
  // const removeFromCart = context.removeFromCart;
  const [quantity, setQty] = useState(1);
  const [quantityError, setQuantityError] = useState(false);
  const updateQty = context.updateQty;
  const [isOpen, setIsOpen] = useState(false);
  const [needReturn, setNeedReturn] = useState(false);
  const [dropdownOpen1, setDropdownOpen1] = useState(false);
  const [dropdownOpen2, setDropdownOpen2] = useState(false);

  const [cartList, setCartList] = useState([]);
  const [total, setTotal] = useState(0);
  const [qtyList, setQtyList] = useState([]);
  const [lineTotal, setLineTotal] = useState(0);
  const debounceRef = useRef(null);
  const router = useRouter();

  useEffect(() => {
    var userInfo = localStorage.getItem("XYCLogin");
    if (userInfo) {
      if (JSON.parse(userInfo).user_guid) {
        getCartInfo({ userGuid: JSON.parse(userInfo).user_guid }).then(res => {
          setCartList(res.data);
          let to = Number(0);
          var qtys = [];
          res.data.map(item => {
            to += parseFloat(item.price * item.quantity);
            qtys.push({
              "product_id": item.product_id,
              "quantity": item.quantity,
              "product_stock": item.product_stock,
              "price": item.price
            })
          })
          setTotal(getTwoDecimal(`${to}`));
          setQtyList(qtys);
        });
      }
    }
  }, [window.onload])

  useEffect(() => {

    var user = localStorage.getItem("XYCLogin")
    if (!user) {
      toast.error("Please Login To Shopping!");
      router.push("/");
    }

    debounceRef.current = debounce((item, quantity) => {
      changeProductCount({
        product_id: item.product_id,
        quantity: quantity
      })
    }, 1000);

    return () => {
      if (debounceRef.current) {
        debounceRef.current.cancel();
      }
    };
  }, [])

  const handleQtyUpdate = (item, quantity) => {
    if (quantity > 0 && quantity) {
      debounceRef.current(item, quantity);
      var newQtys = [];
      qtyList.map(q => {
        if (q.product_id != item.product_id)
          newQtys.push(q);
      });
      newQtys.push({
        "product_id": item.product_id,
        "quantity": quantity,
        "product_stock": item.product_stock,
        "price": item.price
      });
      setQtyList(newQtys);

      var newTotal = 0;
      newQtys.map(nq => {
        newTotal += parseFloat(getTwoDecimal(`${parseFloat(nq.price) * parseFloat(nq.quantity)}`))
      })
      setTotal(getTwoDecimal(`${newTotal}`))
    }
  };

  const removeProduct = (item) => {
    setCartList(v => v.filter(p => p.product_id != item.product_id));
    removeCartProduct({ "product_id": item.product_id });
    toast.success("Product remove succeed!");
    var newTotal = 0;
    qtyList.map(nq => {
      if (nq.product_id != item.product_id) {
        newTotal += parseFloat(getTwoDecimal(`${parseFloat(nq.price) * parseFloat(nq.quantity)}`))
      }
    })
    setQtyList(v => v.filter(p => p.product_id != item.product_id));
    console.log(newTotal)
    setTotal(getTwoDecimal(`${newTotal}`))
  }

  const toggle1 = () => setDropdownOpen((prevState) => !prevState);
  const toggle2 = () => setDropdownOpen((prevState) => !prevState);

  return (
    <div>
      <Modal isOpen={isOpen} centered size="lg">
        <ModalHeader >Order Info</ModalHeader>
        <ModalBody>
          <div className="admin-user-form">
            <Row>
              <Col sm="12">
                <Form className="theme-form">
                  <Row>
                    <Col sm="12">

                    </Col>
                  </Row>

                  <Row>
                    <Col md="4">
                      <Label for="lName">Order Id</Label>
                      <h4>{"2024072214552344123"}</h4>
                    </Col>
                    <Col md="3">
                      <Label for="lName">Product Name</Label>
                      <h4>{"Test Product 1"}</h4>
                    </Col>
                    <Col md="2">
                      <Label for="fname">Quantity</Label>
                      <h4>{"25"}</h4>
                    </Col>
                    <Col md="2">
                      <Label for="fname">Total Price</Label>
                      <h4>{"$25"}</h4>
                    </Col>
                  </Row>
                  <Row>
                    <Col md="4">
                      <Label for="fname">Order Status</Label>
                      <h4>{"Undelivered"}</h4>
                    </Col>
                    <Col md="4">
                      <Label for="fname">Create Date</Label>
                      <h4>{"2024-07-22 11:22:00"}</h4>
                    </Col>
                  </Row>
                  <Row>
                    <Col md="4">
                      <Label for="fname">Tracking Number</Label>
                      {/* 为空则显示未发货 */}
                      <h4>{"None"}</h4>
                    </Col>
                    <Col md="4">
                      <Label for="fname">Tracking Image</Label>
                      {/* 为空则显示未发货 */}
                      <h4>{"None"}</h4>
                      {/* <a>1111111111111111.jpg</a> */}
                    </Col>
                    <Col md="4">
                      <Label for="fname">Deliver Date</Label>
                      {/* 为空则显示未发货 */}
                      {""}
                      {/* <a>1111111111111111.jpg</a> */}
                    </Col>
                  </Row>
                  {
                    needReturn &&
                    <>
                      <Row>
                        <Col md="4">
                          <Label for="fname">Return Tracking Number</Label>
                          {/* 为空则显示未发货 */}
                          <Input type="text" className="form-control" id="lname" name="lname" placeholder="Please Enter" disabled />
                        </Col>
                        <Col md="8">
                          <Label for="fname">Return Tracking Image</Label>
                          {/* 为空则显示未发货 */}
                          {/* <h4>{"Undelivered"}</h4> */}
                          <div><Button disabled color="primary">Upload</Button><a>1111111111111111.jpg</a></div>
                        </Col>
                        <Col md="12">
                          <Label for="zipCode">Return Reason</Label>
                          <Input type="textarea" style={{ height: 100 }} className="form-control" id="productDescription" name="productDescription" placeholder="Product Description, Max length: 400 digits." maxLength={400}
                            required="" />
                        </Col>
                      </Row>
                    </>
                  }
                  <div className="admin-user-form-btn-list">
                    <Row>
                      <Col md="3">
                        <Button size="lg" onClick={() => { setNeedReturn(!needReturn) }}>Return</Button>
                      </Col>
                      <Col md="3">
                      </Col>
                      <Col md="3">
                        {
                          needReturn &&
                          <a href={null} style={{ width: 170, height: 40, fontSize: 12, lineHeight: 1 }} className="btn btn-solid" >Confirm</a>
                        }
                      </Col>
                      <Col md="3">
                        <a href={null} onClick={() => { setIsOpen(false); setNeedReturn(false) }} style={{ width: 170, height: 40, fontSize: 12, lineHeight: 1 }} className="btn btn-solid" >Cancel</a>
                      </Col>
                    </Row>
                  </div>
                </Form>
              </Col>
            </Row>
          </div>
        </ModalBody>
      </Modal>
      <div>
        <Row className="order-list-filter-btn-list">
          <Col md="4">
            <ButtonGroup style={{ marginRight: 20, marginLeft: 80 }}>
              <UncontrolledDropdown>
                <DropdownToggle caret>
                  Filter
                </DropdownToggle>
                <DropdownMenu>
                  <DropdownItem>
                    Undelivered
                  </DropdownItem>
                  <DropdownItem>
                    delivered
                  </DropdownItem>
                  <DropdownItem>
                    Completed
                  </DropdownItem>
                  <DropdownItem>
                    Processing
                  </DropdownItem>
                  <DropdownItem>
                    Returned
                  </DropdownItem>
                </DropdownMenu>
              </UncontrolledDropdown>
            </ButtonGroup>
          </Col>
          <Col md="3">
          </Col>
          <Col md="5"></Col>
        </Row>
      </div>
      {cartList && cartList.length > 0 ? (
        <section className="cart-section section-b-space">
          <Container>
            <Row>
              <Col sm="12">
                <table className="table cart-table table-responsive-xs">
                  <thead>
                    <tr className="table-head">
                      <th scope="col">product</th>
                      <th scope="col">product name</th>
                      <th scope="col">order id</th>
                      <th scope="col">quantity</th>
                      <th scope="col">total price</th>
                      <th scope="col">order status</th>
                      <th scope="col">create date</th>
                      <th scope="col">action</th>
                    </tr>
                  </thead>
                  {cartList.map((item, index) => {
                    return (
                      <tbody key={index}>
                        <tr>
                          <td>
                            <Link href={`/product-details/` + item.product_id}>
                              <a className="order-list-product">
                                <Media
                                  src={item.product_media1 ? `${fileServerUrl}/${item.product_media1}` : `${fileServerUrl}/products/default.jpg`}
                                  alt=""
                                />
                              </a>
                            </Link>
                          </td>
                          <td>
                            <Link href={`/product-details/` + item.product_id}>
                              <a>{item.product_name}</a>
                            </Link>
                          </td>
                          <td>
                            <h2>
                              {symbol}
                              {getTwoDecimal(item.price)}
                            </h2>
                          </td>
                          <td>
                            <h2>
                              {symbol}
                              {getTwoDecimal(item.price)}
                            </h2>
                          </td>
                          <td>
                            <h2 className="td-color">
                              {symbol}
                              {getTwoDecimal(item.price)}
                            </h2>
                          </td>
                          <td>
                            {item.quantity}
                          </td>

                          <td>
                            <h2>
                              {symbol}
                              {getTwoDecimal(`${parseFloat(item.price) * (qtyList.length > 0 ? parseFloat(qtyList.find(q => q.product_id == item.product_id).quantity) : parseFloat(item.quantity))}`)}
                            </h2>
                          </td>
                          <td>
                            <Button color="success" className="admin-product-acion" onClick={() => { setIsOpen(true) }}>View</Button>
                            <Button className="admin-product-acion">Delete</Button>
                          </td>
                        </tr>
                      </tbody>
                    );
                  })}
                </table>
              </Col>
            </Row>
          </Container>
        </section>
      ) : (
        <section className="cart-section section-b-space">
          <Container>
            <Row>
              <Col sm="12">
                <div>
                  <div className="col-sm-12 empty-cart-cls text-center">
                    <Media
                      src={cart}
                      className="img-fluid mb-4 mx-auto"
                      alt=""
                    />
                    <h3>
                      <strong>Your Order Is Empty</strong>
                    </h3>
                  </div>
                </div>
              </Col>
            </Row>
          </Container>
        </section>
      )}
      <div className="order-list-page-select-btn">
        <Button className="page-select-btn1" onClick="">Last Page</Button><span className="page-select-label">{"1"} IN {"5"}</span><Button className="page-select-btn2" onClick="">Next Page</Button>
      </div>
    </div>
  );
};

export default AdminOrderBinPage;
